<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AIEdit 文本校对工具</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <link type="text/css" rel="stylesheet" href="/static/aieditor/style.css">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#3b82f6',
                        secondary: '#64748b',
                        success: '#10b981',
                        warning: '#f59e0b',
                        danger: '#ef4444',
                        info: '#06b6d4',
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .bg-gradient-primary {
                background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);
            }
            .shadow-custom {
                box-shadow: 0 10px 25px -5px rgba(59, 130, 246, 0.1), 0 8px 10px -6px rgba(59, 130, 246, 0.1);
            }
            .editor-height {
                height: calc(100vh - 18rem);
            }
            .suggestion-height {
                height: calc(100vh - 24rem);
            }
        }
    </style>
</head>
<body class="bg-gray-50 min-h-screen flex flex-col">
    <!-- 导航栏 -->
    <nav class="bg-gradient-primary text-white shadow-md">
        <div class="container mx-auto px-4 py-3 flex justify-between items-center">
            <div class="flex items-center space-x-2 cursor-pointer" onclick="window.location.href='{{ url_for('upload_file') }}'">
                <i class="fa fa-arrow-left"></i>
                <i class="fa fa-check-circle text-2xl"></i>
                <h1 class="text-xl font-bold">AIEdit 文本校对工具</h1>
            </div>
            <div class="flex items-center space-x-3">
                <span class="text-sm font-medium">校对结果</span>
                <button id="downloadBtn" class="px-3 py-1.5 bg-white/20 hover:bg-white/30 text-white rounded-lg text-sm transition-all duration-300 flex items-center">
                    <i class="fa fa-download mr-1.5"></i> 下载
                </button>
            </div>
        </div>
    </nav>

    <!-- 主内容区 -->
    <main class="flex-grow container mx-auto px-4 py-6">
        <div class="bg-white rounded-xl shadow-custom overflow-hidden">
            <div class="p-6 border-b border-gray-200">
                <h2 class="text-2xl font-bold text-gray-800">文本校对结果</h2>
                <p class="text-gray-600 mt-1">分析完成，以下是发现的需要修改的地方</p>
            </div>

            <div class="flex flex-col lg:flex-row">
                <!-- 左侧AIEdit编辑器 -->
                <div class="w-full lg:w-1/2 p-6 border-b lg:border-b-0 lg:border-r border-gray-200">
                    <div class="mb-4 flex justify-between items-center">
                        <h3 class="text-lg font-semibold text-gray-700">原文内容</h3>
                        <span class="text-xs text-gray-500">
                            <i class="fa fa-file-text-o mr-1"></i>
                            字符数: <span id="charCount">{{ original_content|length }}</span>
                        </span>
                    </div>
                    <div id="editor" class="border border-gray-300 rounded-lg overflow-hidden h-[500px]" height="500"></div>
                </div>

                <!-- 右侧配置区 -->
                <div class="w-full lg:w-1/2 p-6">
                    <div class="flex justify-between items-center mb-6">
                        <h3 class="text-lg font-semibold text-gray-700">校对建议</h3>
                        <button id="proofreadBtn" class="px-4 py-2 bg-primary text-white rounded-lg font-medium transition-all duration-300 hover:bg-primary/90 hover:shadow-md flex items-center">
                            <i class="fa fa-check-circle mr-2"></i> 立即校对
                        </button>
                    </div>

                    <!-- 筛选区 -->
                    <div class="bg-gray-50 p-4 rounded-lg mb-6">
                        <div class="flex flex-wrap gap-2">
                            <span class="text-sm font-medium text-gray-700 mr-2">筛选:</span>
                            <button class="filter-btn px-3 py-1 rounded-full text-sm flex items-center transition-all duration-300" data-category="all">
                                <span class="mr-1.5">全部</span>
                                <span class="bg-gray-200 text-gray-700 px-2 py-0.5 rounded-full text-xs" id="count-all">0</span>
                            </button>
                            <button class="filter-btn px-3 py-1 rounded-full text-sm flex items-center transition-all duration-300" data-category="错别字">
                                <i class="fa fa-times-circle text-danger mr-1.5"></i>
                                <span>错别字</span>
                                <span class="bg-danger/20 text-danger px-2 py-0.5 rounded-full text-xs" id="count-typo">0</span>
                            </button>
                            <button class="filter-btn px-3 py-1 rounded-full text-sm flex items-center transition-all duration-300" data-category="建议修改">
                                <i class="fa fa-lightbulb-o text-warning mr-1.5"></i>
                                <span>建议修改</span>
                                <span class="bg-warning/20 text-warning px-2 py-0.5 rounded-full text-xs" id="count-suggest">0</span>
                            </button>
                            <button class="filter-btn px-3 py-1 rounded-full text-sm flex items-center transition-all duration-300" data-category="标点">
                                <i class="fa fa-exclamation-circle text-info mr-1.5"></i>
                                <span>标点</span>
                                <span class="bg-info/20 text-info px-2 py-0.5 rounded-full text-xs" id="count-punctuation">0</span>
                            </button>
                            <button class="filter-btn px-3 py-1 rounded-full text-sm flex items-center transition-all duration-300" data-category="敏感词">
                                <i class="fa fa-shield text-success mr-1.5"></i>
                                <span>敏感词</span>
                                <span class="bg-success/20 text-success px-2 py-0.5 rounded-full text-xs" id="count-sensitive">0</span>
                            </button>
                        </div>
                    </div>
                    <!-- 建议列表 -->
                    <div class="border border-gray-300 rounded-lg overflow-hidden suggestion-height overflow-y-auto">
                        <div id="suggestionsList" class="divide-y divide-gray-200">
                            {% for suggestion in suggestions %}
                                {% if suggestion.show %}
                                <div class="p-4 suggestion-item" data-category="{{ suggestion.category }}" data-original="{{ suggestion.original|escape }}" data-corrected="{{ suggestion.corrected|escape }}" data-offset="{{ suggestion.offset }}">
                                    <div class="flex justify-between items-start mb-2">
                                        <span class="px-2 py-1 rounded-full text-xs font-medium
                                            {% if suggestion.category == '错别字' %}bg-danger/20 text-danger{% endif %}
                                            {% if suggestion.category == '建议修改' %}bg-warning/20 text-warning{% endif %}
                                            {% if suggestion.category == '标点' %}bg-info/20 text-info{% endif %}
                                            {% if suggestion.category == '敏感词' %}bg-success/20 text-success{% endif %}">
                                            {{ suggestion.category }}
                                        </span>
                                        <button class="ignore-btn text-gray-400 hover:text-gray-600 transition-colors duration-300">
                                            <i class="fa fa-times-circle"></i>
                                        </button>
                                    </div>
                                    <div class="mb-2">
                                        <p class="text-sm text-gray-600 mb-1">原文:</p>
                                        <p class="text-sm font-mono bg-gray-50 p-2 rounded border border-gray-200 break-words">{{ suggestion.original }}</p>
                                    </div>
                                    <div>
                                        <p class="text-sm text-gray-600 mb-1">建议:</p>
                                        <p class="text-sm font-mono bg-gray-50 p-2 rounded border border-gray-200 break-words">{{ suggestion.corrected }}</p>
                                    </div>
                                    <button class="apply-suggestion mt-3 w-full px-4 py-2 bg-primary/10 text-primary rounded-lg text-sm font-medium hover:bg-primary/20 transition-colors">
                                        应用建议
                                    </button>
                                </div>
                                {% endif %}
                            {% endfor %}

                            {% if not suggestions or not suggestions|selectattr('show')|list %}
                            <div class="p-6 text-center text-gray-500">
                                <i class="fa fa-check-circle text-3xl mb-3 text-success"></i>
                                <p>没有发现需要修改的内容</p>
                            </div>
                            {% endif %}
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </main>

    <!-- 页脚 -->
    <footer class="bg-gray-800 text-white py-6 mt-8">
        <div class="container mx-auto px-4 text-center">
            <p class="text-sm">© 2025 AIEdit 文本校对工具 | 使用AI技术提供智能文本分析</p>
        </div>
    </footer>
    <script type="module">
        var editor;
        var markers = [];
        var currentSuggestions = []; // 存储当前建议列表

        // 页面加载完成后初始化编辑器
        document.addEventListener('DOMContentLoaded', async function() {
            try {
                // 动态导入AiEditor库
                const aiEditorModule = await import('/static/aieditor/index.js');

                // 确认AiEditor已正确加载
                if (typeof aiEditorModule.AiEditor === 'undefined') {
                    throw new Error('AiEditor类未在模块中定义');
                }

                // 使用命名空间访问AiEditor
                const AiEditor = aiEditorModule.AiEditor;

                var originalContent = `{{ original_content | safe }}`;
                var processedContent = originalContent;

                // 为回退的textarea添加下划线标记
                {% if suggestions %}
                    const sortedSuggestions = {{ suggestions | tojson | safe }}.sort((a, b) => b.offset - a.offset);
                    currentSuggestions = sortedSuggestions; // 初始化当前建议

                    sortedSuggestions.forEach(suggestion => {
                        // 使用正则表达式转义特殊字符
                        const escapedOriginal = suggestion.original.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
                        const regex = new RegExp(escapedOriginal, 'g');

                        // 替换文本
                        const replacement = `<span style="color: #de3c36"><u>$&</u></span>`;
                        processedContent = processedContent.replace(regex, replacement);
                    });
                {% endif %}

                // 初始化AIEdit编辑器
                editor = new AiEditor({
                    element: document.getElementById('editor'),
                    content: processedContent,
                    language: 'plaintext',
                    theme: 'light',
                    lineNumbers: true,
                    indentUnit: 4,
                    autoIndent: true,
                    spellcheck: true,
                    highlightActiveLine: true,
                    fontSize: 14,
                    fontFamily: 'Consolas, Monaco, monospace'
                });

                // 检查editor对象是否有效
                if (editor && typeof editor.on === 'function') {
                    // 监听编辑器变化，更新字符计数
                    editor.on('change', updateCharCount);
                    updateCharCount();
                } else {
                    console.warn('编辑器不支持事件监听，字符计数功能将不可用');
                }

                // 高亮所有建议
                highlightAllSuggestions();

                // 初始化筛选功能
                initFiltering();

                // 初始化建议应用功能
                initSuggestionActions();

                // 更新计数显示
                updateCategoryCounts();

                // 初始化下载功能
                initDownloadFunctionality();

            } catch (error) {
                console.error('AIEdit初始化失败:', error);
                fallbackToTextarea();
            }
        });

        // 更新字符计数
        function updateCharCount() {
            const content = editor?.getValue() || '';
            document.getElementById('charCount').textContent = content.length;
        }

        // 高亮所有建议
        function highlightAllSuggestions() {
            // 清除现有标记
            if (markers.length) {
                markers.forEach(marker => marker.clear());
                markers = [];
            }

            // 获取当前筛选的建议
            const visibleSuggestions = document.querySelectorAll('.suggestion-item[style="display: block;"]');

            // 为每个建议添加高亮
            visibleSuggestions.forEach(suggestion => {
                const originalText = suggestion.dataset.original;
                const offset = parseInt(suggestion.dataset.offset);
                const category = suggestion.dataset.category;

                if (!originalText.trim()) return;

                // 根据类别选择高亮样式
                let className = 'text-danger';
                if (category === '建议修改') className = 'text-warning';
                else if (category === '标点') className = 'text-info';
                else if (category === '敏感词') className = 'text-success';

                // 计算文本范围
                if (editor && typeof editor.posFromIndex === 'function') {
                    const content = editor.getValue();
                    const startPos = editor.posFromIndex(offset);
                    const endPos = editor.posFromIndex(offset + originalText.length);

                    // 添加高亮标记
                    if (typeof editor.markText === 'function') {
                        const marker = editor.markText(startPos, endPos, {
                            className: className,
                            title: suggestion.querySelector('.text-gray-600 + p').textContent // 建议文本
                        });

                        markers.push(marker);
                    }
                }
            });
        }

        // 初始化筛选功能
        function initFiltering() {
            document.querySelectorAll('.filter-btn').forEach(btn => {
                btn.addEventListener('click', function() {
                    const category = this.dataset.category;

                    // 更新按钮样式
                    document.querySelectorAll('.filter-btn').forEach(b => {
                        b.classList.remove('bg-primary', 'text-white');
                        b.classList.add('bg-gray-100', 'text-gray-700');
                    });
                    this.classList.remove('bg-gray-100', 'text-gray-700');
                    this.classList.add('bg-primary', 'text-white');

                    // 筛选建议项
                    const items = document.querySelectorAll('.suggestion-item');
                    items.forEach(item => {
                        if (category === 'all' || item.dataset.category === category) {
                            item.style.display = 'block';
                        } else {
                            item.style.display = 'none';
                        }
                    });

                    // 更新高亮
                    highlightAllSuggestions();
                });
            });
        }

        // 初始化建议应用功能
        function initSuggestionActions() {
            // 应用建议
            document.querySelectorAll('.apply-suggestion').forEach(btn => {
                btn.addEventListener('click', function() {
                    const suggestionItem = this.closest('.suggestion-item');
                    const originalText = suggestionItem.dataset.original;
                    const correctedText = suggestionItem.dataset.corrected;
                    const offset = parseInt(suggestionItem.dataset.offset);

                    // 计算替换范围
                    if (editor && editor.getHtml()) {
                        console.log("开始替换文本");
                        const orginalstr = editor.getHtml();

                        // 使用正则表达式转义特殊字符
                        const replacement = `<span style="color: rgb(222, 60, 54)"><u>`+originalText+`</u></span>`;
                        const escapedOriginal = replacement.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
                        const regex = new RegExp(escapedOriginal, 'g');
                        const currentContent = editor.getHtml();
                        editor.setContent(currentContent.replace(regex, correctedText));
                    }

                    // 从DOM中移除当前建议项
                    suggestionItem.remove();

                    // 重新获取所有可见的建议项并更新它们的索引
                    updateSuggestionIndices();

                    // 重新高亮所有建议
                    highlightAllSuggestions();

                    // 显示成功提示
                    showNotification('建议已应用');
                });
            });

            // 忽略建议
            document.querySelectorAll('.ignore-btn').forEach(btn => {
                btn.addEventListener('click', function() {
                    const suggestionItem = this.closest('.suggestion-item');
                    suggestionItem.style.display = 'none';

                    // 更新建议项索引
                    updateSuggestionIndices();

                    // 重新高亮所有建议
                    highlightAllSuggestions();
                });
            });
        }

        // 更新所有建议项的索引
        function updateSuggestionIndices() {
            const visibleSuggestions = document.querySelectorAll('.suggestion-item[style="display: block;"]');

            visibleSuggestions.forEach((item, index) => {
                // 更新应用按钮的data-index
                const applyBtn = item.querySelector('.apply-suggestion');
                if (applyBtn) {
                    applyBtn.dataset.index = index;
                }

                // 更新忽略按钮的data-index
                const ignoreBtn = item.querySelector('.ignore-btn');
                if (ignoreBtn) {
                    ignoreBtn.dataset.index = index;
                }
            });
        }

        // 立即校对
        document.getElementById('proofreadBtn').addEventListener('click', function() {
            const content = editor?.getHtml() || '';
            console.log("开始校对");
            if (!content.trim()) {
                showNotification('请先输入文本内容');
                return;
            }

            // 显示加载状态
            this.disabled = true;
            this.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i> 正在调用大模型校对...';

            // 调用大模型进行文本校对
            callLargeModelForProofread(content)
                .then(newSuggestions => {
                    console.log("1");

                    // 更新当前建议列表
                    currentSuggestions = newSuggestions;
                    console.log("2. 更新建议列表数据结构");

                    // 处理内容并添加建议高亮标记
                    const processedContent = processContentWithSuggestions(content, newSuggestions);
                    console.log("3. 处理内容并添加高亮标记");

                    // 更新建议列表UI
                    updateSuggestionList(newSuggestions);
                    console.log("3");

                    // 更新类别计数
                    updateCategoryCountsByContent(newSuggestions);
                    console.log("4");
                    // 重新高亮所有建议
                    highlightAllSuggestions();
                    console.log("5");
                    showNotification('文本校对完成');
                })
                .catch(error => {
                    showNotification('校对失败，请检查网络连接后重试');
                })
                .finally(() => {
                    // 恢复按钮状态
                    this.disabled = false;
                    this.innerHTML = '<i class="fa fa-check-circle mr-2"></i> 立即校对';
                });
        });

        // 调用大模型进行文本校对
        function callLargeModelForProofread(text) {
            return new Promise((resolve, reject) => {
                // 这里应替换为实际的大模型API调用
                // 示例使用fetch发送POST请求到后端API
                fetch('/api/proofread', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ text: text }),
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP错误! 状态码: ${response.status}`);
                    }
                    return response.json();
                })
                .then(data => {
                    // 详细打印整个响应数据
                    console.log("完整API响应数据:", data);

                    // 检查suggestions字段
                    if (Array.isArray(data.suggestions)) {
                        console.log("找到suggestions数组，长度:", data.suggestions.length);
                        resolve(data.suggestions);
                    } else {
                        // 检查其他可能的字段
                        console.log("未找到suggestions数组，检查其他字段:", Object.keys(data));

                        // 尝试其他可能的字段名
                        if (Array.isArray(data.results)) {
                            console.log("找到results数组，可能是替代字段:", data.results);
                            resolve(data.results);
                        } else if (Array.isArray(data.data)) {
                            console.log("找到data数组，可能是替代字段:", data.data);
                            resolve(data.data);
                        } else {
                            throw new Error('大模型返回数据格式不正确，缺少建议数组');
                        }
                    }
                })
                .catch(error => {
                    reject(error);
                });
            });
        }

        // 更新建议列表UI
        function updateSuggestionList(suggestions) {
            const suggestionsList = document.getElementById('suggestionsList');
            suggestionsList.innerHTML = '';

            if (suggestions && suggestions.length > 0) {
                suggestions.forEach(suggestion => {
                    const suggestionItem = document.createElement('div');
                    suggestionItem.className = 'p-4 suggestion-item';
                    suggestionItem.dataset.category = suggestion.category || '未知';
                    suggestionItem.dataset.original = suggestion.original || '';
                    suggestionItem.dataset.corrected = suggestion.corrected || '';
                    suggestionItem.dataset.offset = suggestion.offset || 0;
                    suggestionItem.style.display = 'block'; // 初始显示所有建议

                    suggestionItem.innerHTML = `
                        <div class="flex justify-between items-start mb-2">
                            <span class="px-2 py-1 rounded-full text-xs font-medium
                                ${getCategoryClass(suggestion.category || '未知')}">
                                ${suggestion.category || '未知'}
                            </span>
                            <button class="ignore-btn text-gray-400 hover:text-gray-600 transition-colors duration-300">
                                <i class="fa fa-times-circle"></i>
                            </button>
                        </div>
                        <div class="mb-2">
                            <p class="text-sm text-gray-600 mb-1">原文:</p>
                            <p class="text-sm font-mono bg-gray-50 p-2 rounded border border-gray-200 break-words">${suggestion.original || ''}</p>
                        </div>
                        <div>
                            <p class="text-sm text-gray-600 mb-1">建议:</p>
                            <p class="text-sm font-mono bg-gray-50 p-2 rounded border border-gray-200 break-words">${suggestion.corrected || ''}</p>
                        </div>
                        <button class="apply-suggestion mt-3 w-full px-4 py-2 bg-primary/10 text-primary rounded-lg text-sm font-medium hover:bg-primary/20 transition-colors">
                            应用建议
                        </button>
                    `;

                    suggestionsList.appendChild(suggestionItem);
                });

                // 初始化新添加的建议项交互
                initSuggestionActions();
            } else {
                // 没有建议时显示空状态
                suggestionsList.innerHTML = `
                    <div class="p-6 text-center text-gray-500">
                        <i class="fa fa-check-circle text-3xl mb-3 text-success"></i>
                        <p>没有发现需要修改的内容</p>
                    </div>
                `;
            }
        }

        // 根据类别获取对应的CSS类
        function getCategoryClass(category) {
            switch(category) {
                case '错别字': return 'bg-danger/20 text-danger';
                case '建议修改': return 'bg-warning/20 text-warning';
                case '标点': return 'bg-info/20 text-info';
                case '敏感词': return 'bg-success/20 text-success';
                default: return 'bg-gray-200 text-gray-700';
            }
        }

        // 处理内容并添加建议高亮标记
        function processContentWithSuggestions(content, suggestions) {
            // 复制原始内容
            var processed = content;

            // 按偏移量降序排列建议，避免替换后偏移量变化
            const sortedSuggestions = [...suggestions].sort((a, b) => b.offset - a.offset);

            var processedContent = content;

            // 为每个建议添加HTML标记
            sortedSuggestions.forEach(suggestion => {
                // 使用正则表达式转义特殊字符
                const escapedOriginal = suggestion.original.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
                const regex = new RegExp(escapedOriginal, 'g');

                // 替换文本
                const replacement = `<span style="color: #de3c36"><u>$&</u></span>`;
                processedContent = processedContent.replace(regex, replacement);
            });

            editor.setContent(processedContent)
        }

        // 更新类别计数显示
        function updateCategoryCounts() {
            const typoCount = currentSuggestions.filter(s => s.category === '错别字').length;
            const suggestCount = currentSuggestions.filter(s => s.category === '建议修改').length;
            const punctuationCount = currentSuggestions.filter(s => s.category === '标点').length;
            const sensitiveCount = currentSuggestions.filter(s => s.category === '敏感词').length;
            const totalCount = typoCount + suggestCount + punctuationCount + sensitiveCount;

            document.getElementById('count-all').textContent = totalCount;
            document.getElementById('count-typo').textContent = typoCount;
            document.getElementById('count-suggest').textContent = suggestCount;
            document.getElementById('count-punctuation').textContent = punctuationCount;
            document.getElementById('count-sensitive').textContent = sensitiveCount;
        }

        // 更新类别计数显示
        function updateCategoryCountsByContent(currentSuggestions) {
            const typoCount = currentSuggestions.filter(s => s.category === '错别字').length;
            const suggestCount = currentSuggestions.filter(s => s.category === '建议修改').length;
            const punctuationCount = currentSuggestions.filter(s => s.category === '标点').length;
            const sensitiveCount = currentSuggestions.filter(s => s.category === '敏感词').length;
            const totalCount = typoCount + suggestCount + punctuationCount + sensitiveCount;

            document.getElementById('count-all').textContent = totalCount;
            document.getElementById('count-typo').textContent = typoCount;
            document.getElementById('count-suggest').textContent = suggestCount;
            document.getElementById('count-punctuation').textContent = punctuationCount;
            document.getElementById('count-sensitive').textContent = sensitiveCount;
        }

        // 显示通知
        function showNotification(message) {
            const notification = document.createElement('div');
            notification.className = 'fixed top-4 right-4 bg-success text-white px-4 py-2 rounded-lg shadow-lg z-50';
            notification.textContent = message;
            document.body.appendChild(notification);

            setTimeout(() => {notification.remove();}, 3000);
        }

        // 回退到原生textarea
        function fallbackToTextarea() {
            const editorContainer = document.getElementById('editor');
            editorContainer.innerHTML = `
                <textarea id="fallbackTextarea" class="w-full h-full p-4 border border-gray-300 rounded-lg font-mono text-sm resize-none" oninput="fallbackUpdateCharCount()">
                    {{ original_content }}
                </textarea>
            `;

            // 创建一个模拟editor对象
            editor = {
                getValue: () => document.getElementById('fallbackTextarea').value,
                on: (event, callback) => {
                    if (event === 'change') {
                        document.getElementById('fallbackTextarea').addEventListener('input', callback);
                    }
                },
                posFromIndex: (offset) => {
                    // 模拟位置计算
                    const textarea = document.getElementById('fallbackTextarea');
                    const text = textarea.value;
                    let line = 0;
                    let ch = 0;

                    for (let i = 0; i < offset; i++) {
                        if (text[i] === '\n') {
                            line++;
                            ch = 0;
                        } else {
                            ch++;
                        }
                    }

                    return { line, ch };
                },
                replaceRange: (text, start, end) => {
                    const textarea = document.getElementById('fallbackTextarea');
                    const value = textarea.value;

                    // 计算索引位置
                    let startIndex = 0;
                    for (let i = 0; i < start.line; i++) {
                        startIndex = value.indexOf('\n', startIndex) + 1;
                    }
                    startIndex += start.ch;

                    let endIndex = startIndex;
                    for (let i = 0; i < (end.line - start.line); i++) {
                        endIndex = value.indexOf('\n', endIndex) + 1;
                    }
                    endIndex += (end.ch - start.ch);

                    // 替换文本
                    textarea.value = value.substring(0, startIndex) + text + value.substring(endIndex);
                    textarea.dispatchEvent(new Event('input'));
                }
            };

            // 初始化回退编辑器功能
            const textarea = document.getElementById('fallbackTextarea');
            document.getElementById('charCount').textContent = textarea.value.length;

            // 更新字符计数
            window.fallbackUpdateCharCount = function() {
                document.getElementById('charCount').textContent = textarea.value.length;
            };

            // 模拟高亮功能
            window.fallbackHighlightSuggestions = function() {
                // 清除现有高亮
                const existingHighlights = editorContainer.querySelectorAll('.fallback-highlight');
                existingHighlights.forEach(el => el.remove());

                // 创建新的高亮层
                const contentDiv = document.createElement('div');
                contentDiv.className = 'absolute inset-0 p-4 pointer-events-none fallback-highlight';
                contentDiv.style.whiteSpace = 'pre-wrap';
                contentDiv.style.wordBreak = 'break-word';
                contentDiv.style.fontFamily = 'Consolas, Monaco, monospace';
                contentDiv.style.fontSize = '0.875rem';
                contentDiv.style.lineHeight = '1.5';
                contentDiv.style.color = 'transparent';

                let html = textarea.value
                    .replace(/&/g, '&amp;')
                    .replace(/</g, '&lt;')
                    .replace(/>/g, '&gt;')
                    .replace(/\n/g, '<br>');

                // 应用高亮
                const visibleSuggestions = document.querySelectorAll('.suggestion-item[style="display: block;"]');
                visibleSuggestions.forEach(suggestion => {
                    const originalText = suggestion.dataset.original;
                    const offset = parseInt(suggestion.dataset.offset);
                    const category = suggestion.dataset.category;

                    if (!originalText.trim()) return;

                    let highlightClass = 'bg-red-100 border-red-500';
                    if (category === '建议修改') highlightClass = 'bg-yellow-100 border-yellow-500';
                    else if (category === '标点') highlightClass = 'bg-blue-100 border-blue-500';
                    else if (category === '敏感词') highlightClass = 'bg-green-100 border-green-500';

                    const start = offset;
                    const end = offset + originalText.length;
                    const prefix = html.substring(0, start);
                    const highlighted = `<span class="border-b-2 px-1 ${highlightClass}" title="${suggestion.querySelector('.text-gray-600 + p').textContent}">${originalText}</span>`;
                    const suffix = html.substring(end);

                    html = prefix + highlighted + suffix;
                });

                contentDiv.innerHTML = html;
                editorContainer.appendChild(contentDiv);
            };

            // 初始化回退高亮
            fallbackHighlightSuggestions();

            // 筛选时更新高亮
            document.querySelectorAll('.filter-btn').forEach(btn => {
                btn.addEventListener('click', fallbackHighlightSuggestions);
            });
        }

        // 初始化下载功能
        function initDownloadFunctionality() {
            const downloadBtn = document.getElementById('downloadBtn');
            if (downloadBtn) {
                downloadBtn.addEventListener('click', downloadEditedContent);
            }
        }

        // 下载编辑后的内容
        function downloadEditedContent() {
            var content = editor.getHtml();

            // 清理HTML标签（如果有）
            content = content.replace(/<[^>]+>/g, '');

            // 创建下载文件
            const blob = new Blob([content], { type: 'text/plain;charset=utf-8' });
            const url = URL.createObjectURL(blob);

            // 创建下载链接
            const a = document.createElement('a');
            a.href = url;
            a.download = `校对后的文本_${new Date().toISOString().slice(0,19).replace(/:/g,'-')}.txt`;
            document.body.appendChild(a);
            a.click();

            // 清理资源
            setTimeout(() => {
                document.body.removeChild(a);
                URL.revokeObjectURL(url);
            }, 0);

            showNotification('文本已成功下载');
        }
    </script>
</body>
</html>
